<template>
  <div class="overview-container">
    <div class="overview-grid">
      <!-- 欢迎卡片 -->
      <el-card class="welcome-card">
        <template #header>
          <div class="card-header-with-select">
            <div class="welcome-header">
              <h2>欢迎回来，{{ user.name }}</h2>
              <p class="welcome-subtitle">今天是 {{ currentDate }}，继续加油！</p>
            </div>
            <!-- 课程选择下拉栏移至右上角 -->
            <div class="course-selector">
              <el-select v-model="selectedCourse" placeholder="选择课程" @change="handleCourseChange" size="small">
                <el-option label="全部课程" :value="0"></el-option>
                <el-option v-for="course in courses" :key="course.id" :label="course.name" :value="course.id"></el-option>
              </el-select>
            </div>
          </div>
        </template>
        <div class="welcome-stats">
          <div class="stat-item">
            <div class="stat-value">{{ stats.studyDays }}</div>
            <div class="stat-label">学习天数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ stats.completedQuestions }}</div>
            <div class="stat-label">完成题目</div>
            <el-button type="text" @click="refreshStats" :loading="refreshing" class="refresh-btn">
              <i class="el-icon-refresh"></i>
            </el-button>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ stats.accuracy }}%</div>
            <div class="stat-label">正确率</div>
          </div>
        </div>
      </el-card>

      <!-- 消息通知卡片 -->
      <MessageCard />

      <!-- 学习进度卡片 -->
      <el-card class="progress-card">
        <template #header>
          <div class="card-header">
            <h3>学习进度</h3>
            <el-button type="primary" link @click="goToProgress">查看详情</el-button>
          </div>
        </template>
        <div class="progress-content">
          <div v-if="progressList.length === 0" class="empty-state">
            暂无学习进度数据
          </div>
          <div v-else class="progress-list">
            <!-- 总体完成率 - 保留进度条 -->
            <div class="progress-item">
              <div class="progress-label">
                <i class="el-icon-trophy progress-icon"></i>
                <span class="item-name">总体完成率</span>
              </div>
              <div class="progress-bar-wrapper">
                <el-progress 
                  :percentage="progressList[0].percent" 
                  :stroke-width="14"
                  :color="getProgressColor(progressList[0].percent)"
                />
                <span class="progress-value">{{ progressList[0].percent }}%</span>
              </div>
            </div>

            <!-- 学习时长 - 改为数据卡片 -->
            <div class="data-item">
              <div class="data-icon">
                <i class="el-icon-time"></i>
              </div>
              <div class="data-info">
                <div class="data-label">学习时长</div>
                <div class="data-value">{{ progressList[1]?.originalValue || 0 }} 分钟</div>
              </div>
            </div>

            <!-- 完成题目 - 改为数据卡片 -->
            <div class="data-item">
              <div class="data-icon">
                <i class="el-icon-check"></i>
              </div>
              <div class="data-info">
                <div class="data-label">完成题目</div>
                <div class="data-value">{{ progressList[2]?.originalValue || 0 }} 题</div>
              </div>
            </div>

            <!-- 添加正确率数据卡片 -->
            <div class="data-item">
              <div class="data-icon">
                <i class="el-icon-star-on"></i>
              </div>
              <div class="data-info">
                <div class="data-label">正确率</div>
                <div class="data-value">{{ stats.accuracy }}%</div>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 最近测试记录 -->
      <el-card class="test-card">
        <template #header>
          <div class="card-header">
            <h3>最近测试</h3>
            <el-button type="primary" link @click="goToTest">查看全部</el-button>
          </div>
        </template>
        <div class="test-list">
          <div v-for="test in recentTests" :key="test.id" class="test-item">
            <div class="test-info">
              <span class="test-name">{{ test.name }}</span>
              <el-tag :type="getScoreType(test.score)" size="small">
                {{ test.score }}分
              </el-tag>
            </div>
            <div class="test-meta">
              <span class="test-time">{{ test.time }}</span>
              <span class="test-duration">{{ test.duration }}</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import MessageCard from './MessageCard.vue'
import { useUserStore } from '../../../store/UserStore'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)

const user = ref({
  name: userInfo.value?.username || '未知用户'
})

const currentDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
})

const stats = ref({
  studyDays: 0,
  completedQuestions: 0,
  accuracy: 0
})

const progressList = ref([])

const refreshing = ref(false)
let refreshTimer = null

// 课程相关数据
const selectedCourse = ref(0) // 0表示全部课程
const courses = ref([
  { id: 1, name: '数据结构' },
  { id: 2, name: '操作系统' },
  { id: 3, name: '计算机组成原理' },
  { id: 4, name: '计算机网络' } // 添加第四个课程
])

// 处理课程选择变化
const handleCourseChange = async (courseId) => {
  console.log('选择的课程ID:', courseId)
  await fetchUserStats()
}

// 获取用户学习统计数据
const fetchUserStats = async () => {
  if (!userInfo.value?.userId) return

  try {
    // 获取用户注册信息，计算学习天数
    const userResponse = await axios.get(`http://localhost:8080/user/user_find/${userInfo.value.userId}`)
    if (userResponse.data) {
      const registerDate = new Date(userResponse.data.registerTime)
      const today = new Date()
      const diffTime = Math.abs(today - registerDate)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      stats.value.studyDays = diffDays
    }

    // 直接获取用户完成题目数量 - 使用更直接的接口
    try {
      // 尝试从用户练习记录获取完成题目数量
      const practiceResponse = await axios.get(`http://localhost:8080/userPractices/user/${userInfo.value.userId}`)
      if (practiceResponse.data && Array.isArray(practiceResponse.data)) {
        // 计算用户完成的题目总数
        const completedQuestions = practiceResponse.data.reduce((total, practice) => {
          return total + (practice.completedCount || 0)
        }, 0)
        stats.value.completedQuestions = completedQuestions
        console.log('从练习记录获取的完成题目数:', completedQuestions)
      }
    } catch (practiceError) {
      console.error('获取练习记录失败:', practiceError)
    }

    // 根据选择的课程ID获取分析数据
    if (selectedCourse.value === 0) {
      // 使用auto-analyze接口但不提供courseId参数，获取全部课程的汇总分析数据
      const allCoursesResponse = await axios.get(`http://localhost:8080/useranalysis/auto-analyze`, {
        params: { 
          userId: userInfo.value.userId
          // 不提供courseId参数，后端将返回所有课程的汇总数据
        }
      })

      if (allCoursesResponse.data) {
        // 全部课程时返回的数据结构与单个课程不同
        const analysisData = allCoursesResponse.data;
        console.log('获取到的全部课程分析数据:', analysisData);
        
        // 如果从练习记录获取失败，则使用分析数据
        if (!stats.value.completedQuestions) {
          stats.value.completedQuestions = analysisData.totalQuestions || 0;
        }
        // 使用平均正确率
        stats.value.accuracy = analysisData.averageAccuracyRate ? Math.round(analysisData.averageAccuracyRate * 100) : 0;
      }
    } else {
      // 使用单课程分析接口
      const analysisResponse = await axios.get(`http://localhost:8080/useranalysis/auto-analyze`, {
        params: { 
          userId: userInfo.value.userId,
          courseId: selectedCourse.value
        }
      })

      if (analysisResponse.data && analysisResponse.data.success && analysisResponse.data.data) {
        const analysisData = analysisResponse.data.data;
        // 如果从练习记录获取失败，则使用分析数据
        if (!stats.value.completedQuestions) {
          stats.value.completedQuestions = analysisData.totalQuestions || 0;
        }
        stats.value.accuracy = analysisData.accuracyRate ? Math.round(analysisData.accuracyRate * 100) : 0;
        console.log('获取到的单课程分析数据:', analysisData);
      }
    }

    // 如果上述方法都失败，回退到原来的方法
    if (!stats.value.completedQuestions || stats.value.accuracy === 0) {
      const fallbackResponse = await axios.get(`http://localhost:8080/useranalysis/findbyuserid`, {
        params: { userId: userInfo.value.userId }
      })

      if (fallbackResponse.data && fallbackResponse.data.length > 0) {
        const latestAnalysis = fallbackResponse.data[fallbackResponse.data.length - 1]
        // 如果从练习记录获取失败，则使用分析数据
        if (!stats.value.completedQuestions) {
          stats.value.completedQuestions = latestAnalysis.totalQuestions || 0
        }
        stats.value.accuracy = latestAnalysis.accuracyRate ? Math.round(latestAnalysis.accuracyRate * 100) : 0
      }
    }
  } catch (error) {
    console.error('获取用户统计数据失败:', error)
    ElMessage.warning('获取学习统计数据失败，请稍后重试')
  }
}

// 手动刷新统计数据
const refreshStats = async () => {
  if (refreshing.value) return
  
  refreshing.value = true
  try {
    await fetchUserStats()
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败')
  } finally {
    refreshing.value = false
  }
}

// 设置定时刷新
const setupRefreshTimer = () => {
  // 每60秒刷新一次数据
  refreshTimer = setInterval(() => {
    console.log('定时刷新数据...')
    fetchUserStats()
  }, 60000) // 60秒
}

// 监听路由变化
watch(() => route.path, (newPath) => {
  if (newPath.includes('user-center')) {
    nextTick(() => {
      refreshStats()
    })
  }
})

// 获取最近测试记录
const fetchRecentTests = async () => {
  if (!userInfo.value?.userId) return

  try {
    const response = await axios.get(`http://localhost:8080/user-exams/papers/${userInfo.value.userId}`)
    if (response.data && Array.isArray(response.data)) {
      recentTests.value = response.data
        .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
        .slice(0, 3)
        .map(test => ({
          id: test.examId,
          name: test.paperName,
          score: test.userScore,
          time: new Date(test.createTime).toLocaleString(),
          duration: `${Math.floor(test.duration / 60)}分钟`
        }))
    }
  } catch (error) {
    console.error('获取测试记录失败:', error)
  }
}

// 获取学习进度数据
const fetchLearningProgress = async () => {
  if (!userInfo.value?.userId) {
    console.log('[学习进度] 用户未登录或ID无效，终止获取学习进度')
    return
  }

  try {
    console.log('[学习进度] 开始获取学习进度数据')
    console.log('[学习进度] 请求参数:', { userId: userInfo.value.userId })
    
    // 获取课程进度
    const courseIds = [1, 2, 3, 4]
    const uid = userInfo.value.userId
    const courseProgresses = []
    
    // 获取所有课程的进度
    for (const courseId of courseIds) {
      try {
        const { data } = await axios.get('http://localhost:8080/userPractices/point-progress', {
          params: { userId: uid, courseId }
        })
        if (data && typeof data.progress === 'number') {
          courseProgresses.push(Math.round(data.progress))
        } else if (data && data.practicedCount !== undefined && data.totalCount) {
          courseProgresses.push(Math.round((data.practicedCount / data.totalCount) * 100))
        } else {
          courseProgresses.push(0)
        }
      } catch (e) {
        console.error(`获取课程${courseId}进度失败:`, e)
        courseProgresses.push(0)
      }
    }
    
    // 计算平均完成率
    const averageCompletionRate = courseProgresses.length > 0 
      ? courseProgresses.reduce((sum, progress) => sum + progress, 0) / courseProgresses.length
      : 0
    
    // 获取学习时长
    let totalStudyTime = 0
    try {
      const practiceResponse = await axios.get(`http://localhost:8080/userPractices/user/${uid}`)
      if (practiceResponse.data && Array.isArray(practiceResponse.data)) {
        totalStudyTime = practiceResponse.data.reduce((sum, practice) => {
          return sum + (practice.duration || 0)
        }, 0)
      }
    } catch (error) {
      console.error('获取学习时长失败:', error)
    }
    
    // 获取完成题目数量
    let completedCount = 0
    let totalCount = 0
    try {
      const analysisResponse = await axios.get(`http://localhost:8080/useranalysis/auto-analyze`, {
        params: { userId: uid }
      })
      if (analysisResponse.data) {
        completedCount = analysisResponse.data.totalQuestions || 0
        // 假设总题目数是完成题目的150%（如果后端没有提供）
        totalCount = completedCount * 1.5
      }
    } catch (error) {
      console.error('获取题目完成情况失败:', error)
    }
    
    // 构建进度列表
    progressList.value = [
      {
        name: '总体完成率',
        percent: Math.round(averageCompletionRate),
        originalValue: averageCompletionRate
      },
      {
        name: '学习时长',
        percent: Math.min(100, Math.round(totalStudyTime / 60)), // 将秒转换为分钟，并限制最大值为100%
        originalValue: Math.round(totalStudyTime / 60) // 存储原始分钟数
      },
      {
        name: '完成题目',
        percent: totalCount > 0 ? Math.round((completedCount / totalCount) * 100) : 0,
        originalValue: completedCount
      }
    ]
    
    console.log('[学习进度] 处理后的进度列表:', progressList.value)
    console.log('[学习进度] 进度数据获取成功')
  } catch (error) {
    console.error('[学习进度] 获取学习进度失败:', error)
    console.error('[学习进度] 错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
      url: error.config?.url
    })
    ElMessage.error('获取学习进度失败')
  }
}

// 修改进度条显示文本
const getProgressText = (item) => {
  if (item.name === '学习时长') {
    return `${item.originalValue || Math.round(item.percent)}分钟`
  }
  return `${item.percent}%`
}

// 获取进度条颜色的方法
const getProgressColor = (percent) => {
  if (percent >= 80) return '#67C23A'  // 绿色
  if (percent >= 60) return '#409EFF'  // 蓝色
  if (percent >= 40) return '#E6A23C'  // 橙色
  return '#F56C6C'  // 红色
}

// 获取图标类名
const getIconClass = (name) => {
  switch (name) {
    case '总体完成率': return 'el-icon-trophy';
    case '学习时长': return 'el-icon-time';
    case '完成题目': return 'el-icon-check';
    default: return 'el-icon-star-on';
  }
};

// 初始化数据
onMounted(async () => {
  if (!userInfo.value) {
    await new Promise(resolve => setTimeout(resolve, 1000))
  }
  
  // 确保每次进入组件时都调用分析接口更新用户数据
  try {
    console.log('自动调用分析接口更新用户数据...')
    const userId = userInfo.value?.userId
    if (userId) {
      // 使用auto-analyze接口但不提供courseId参数，获取全部课程的汇总分析数据
      const analyzeResponse = await axios.get(`http://localhost:8080/useranalysis/auto-analyze`, {
        params: { 
          userId: userId
          // 不提供courseId参数，后端将返回所有课程的汇总数据
        }
      })
      console.log('用户全部课程分析数据已更新:', analyzeResponse.data)
    }
  } catch (error) {
    console.error('自动更新用户分析数据失败:', error)
  }
  
  await Promise.all([
    fetchUserStats(),
    fetchRecentTests(),
    fetchLearningProgress()
  ])
  
  // 设置定时刷新
  setupRefreshTimer()
})

// 清理定时器
onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})

// 监听用户信息变化
watch(userInfo, (newValue) => {
  if (newValue) {
    fetchUserStats()
    fetchRecentTests()
    fetchLearningProgress()
  }
}, { deep: true })

// 保留原有的其他功能
const recentTests = ref([])

const getScoreType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 80) return 'warning'
  return 'danger'
}

const goToProgress = () => {
  router.push('/home/user-center/progress')
}

const goToTest = () => {
  router.push('/home/user-center/test')
}
</script>

<style scoped>
.overview-container {
  padding: 20px; /* 恢复外部容器的内边距 */
  margin: 0 auto; /* 水平居中 */
  margin-top: 0 !important; /* 保留外部容器与顶部菜单衔接 */
  max-width: 1200px; /* 恢复最大宽度 */
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 恢复 ElCard 默认的 body 内边距 */
:deep(.el-card__body) {
  padding: 20px !important; /* 恢复 ElCard 默认的内边距 */
}

.overview-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
  padding: 0; /* 移除 padding */
}

.welcome-card {
  grid-column: span 2;
  background: linear-gradient(135deg, #6b9bd2 0%, #8bb6e8 100%);
  color: white;
  padding: 0; /* 移除 padding */
}

/* 调整卡片头部样式，使标题和下拉框在同一行 */
.card-header-with-select {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.welcome-header {
  flex: 1;
}

.course-selector {
  margin-left: 20px;
  min-width: 150px;
}

/* 移除之前的样式 */
.welcome-card :deep(.el-card__header) {
  padding-bottom: 0;
}

.welcome-header h2 {
  font-size: 1.8rem;
  margin: 0 0 8px 0;
}

.welcome-subtitle {
  font-size: 1rem;
  opacity: 0.9;
  margin: 0;
}

.welcome-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  text-align: center;
  padding: 0 20px 20px 20px; /* 恢复内部 padding */
}

.stat-item {
  padding: 16px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  position: relative; /* 添加相对定位以便放置刷新按钮 */
}

.stat-value {
  font-size: 2rem;
  font-weight: 600;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 0.9rem;
  opacity: 0.9;
}

.refresh-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  font-size: 14px;
  opacity: 0.7;
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  opacity: 1;
  transform: rotate(180deg);
}

.progress-card,
.test-card {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(107, 155, 210, 0.1);
  box-shadow: 0 8px 32px rgba(107, 155, 210, 0.1);
  padding: 20px; /* 恢复 padding */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  color: #4a6fa5;
  font-size: 1.1rem;
  margin: 0;
}

.progress-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
  padding: 0 20px;
}

.progress-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.progress-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 15px;
  background: rgba(107, 155, 210, 0.05);
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(107, 155, 210, 0.1);
  transition: all 0.3s ease;
}

.progress-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 15px rgba(107, 155, 210, 0.2);
}

.progress-label {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.progress-icon {
  font-size: 20px;
  color: #4a6fa5;
  margin-right: 8px;
}

.item-name {
  font-size: 1rem;
  color: #4a6fa5;
  font-weight: 600;
}

.progress-bar-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.progress-bar-wrapper .el-progress {
  flex-grow: 1;
}

.progress-value {
  font-size: 0.95rem;
  color: #6b8bb0;
  min-width: 60px;
  text-align: right;
}

.data-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background: rgba(107, 155, 210, 0.05);
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(107, 155, 210, 0.1);
  transition: all 0.3s ease;
}

.data-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 15px rgba(107, 155, 210, 0.2);
}

.data-icon {
  font-size: 24px;
  color: #4a6fa5;
  margin-right: 16px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(107, 155, 210, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.data-info {
  flex: 1;
}

.data-label {
  font-size: 14px;
  color: #6b8bb0;
  margin-bottom: 4px;
}

.data-value {
  font-size: 20px;
  font-weight: 600;
  color: #4a6fa5;
}

.empty-state {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-size: 16px;
}

.test-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.test-item {
  padding: 12px; /* 恢复 padding */
  background: rgba(107, 155, 210, 0.05);
  border-radius: 8px;
}

.test-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.test-name {
  color: #4a6fa5;
  font-weight: 500;
}

.test-meta {
  display: flex;
  justify-content: space-between;
  color: #6b8bb0;
  font-size: 0.9rem;
}

:deep(.el-progress-bar__outer) {
  background-color: rgba(107, 155, 210, 0.15);
  border-radius: 7px;
}

:deep(.el-progress-bar__inner) {
  border-radius: 7px;
  transition: all 0.3s ease-in-out;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #6b9bd2, #8bb6e8);
  border: none;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5a8bc1, #7aa5d7);
  transform: translateY(-1px);
}

@media (max-width: 1200px) {
  .overview-grid {
    grid-template-columns: 1fr;
  }

  .welcome-card {
    grid-column: span 1;
  }
}

@media (max-width: 768px) {
  .welcome-stats {
    grid-template-columns: 1fr;
  }

  .progress-content {
    gap: 16px;
  }
}
</style> 